
const { sqlCheckType, err_reply, success_reply, success_reply2, registerResultType } = require('../types/type.js') // 引入枚举类型、响应

var dbConfig = require('../../util/dbconfig.js') // 引入dbconfig
const { json } = require('express')
const dbconfig = require('../../util/dbconfig.js')
const { p_register } = require('../login/login_request.js')
const { validateLoginState } = require('../base/base_validate.js')
const { check_if_exists } = require('../other/other_request.js')

// const isHave = (param) => {
//   if (param && param.length > 0) {
//     return true
//   }
//   return false
// }

/** 
 *  @description 用户增加
 * */ 
const user_add = async (req, res) => {
  // 1、校验登录状态
  const validateLogin = await validateLoginState(res, req, 'post', 'user_add')
  if (!validateLogin) return
  
  console.log('\nuser/add 请求')
  console.log(JSON.stringify(req.body))
  
  // 2、注册
  const [result, code, insertId] = await p_register(req, res, false, false, null)
  console.log('\nuser_add   打印注册结果：')
  console.log(result)
  console.log(code)
  console.log(insertId)
  
  // 注册出错处理
  if(!result) {
    const err_msg = ''
    if(code == registerResultType.ALREADY_EXISTS) err_msg = '用户已经存在'
    if(code == registerResultType.FALSE) err_msg = '注册出错'
    err_reply('user/add', res, err_msg)
    return
  }
  // return
  // 3、拿到用户的信息，更新用户表
  const nick_name = req.body.nick_name
  const sex = req.body.sex
  const phone = req.body.phone
  const head_url = req.body.head_url
  const state = req.body.state
  const role_id = req.body.role_id
  const department_id = req.body.department_id
  // SQL
  const sql_update = `UPDATE userInfo SET  nick_name = '${nick_name}' , sex = '${sex}', phone = '${phone}',
   head_url = '${head_url}', state = '${state}', role_id = '${role_id}', department_id = '${department_id}' 
   WHERE user_id = ${insertId};`

  // 发送请求
  dbconfig.sqlConnect(sql_update, [], (err, data) => {
    if(err) {
      console.log('新增出错')
      console.log('打印SQL语句' + JSON.stringify(sql_update))
      console.log(JSON.stringify(err))
      err_reply('user/add', res, err.sqlMessage)
    } else{
      console.log('用户新增成功')
      console.log(data)
      if (!data.affectedRows || data.affectedRows == 0){
        console.log(`该新增的insertId异常`)
        // 响应客户端请求
        err_reply('/user/add',res,`用户新增请求异常`)
        return
      }
      // 响应客户端请求
      success_reply('user/add', res, '用户新增成功！', insertId ?? '')
    }
  })
}

/** 
 *  @description 用户修改
 * */ 
const user_update = async (req, res) => {
  // 1、校验登录状态
  const validateLogin = await validateLoginState(res, req, 'post', 'user_update')
  if (!validateLogin) return
  
  console.log('\nuser/update 请求')
  console.log(JSON.stringify(req.body))
  
  // 3、拿到用户的信息，更新用户表
  const update_id = req.body.user_id
  const nick_name = req.body.nick_name
  const sex = req.body.sex
  const phone = req.body.phone
  const head_url = req.body.head_url
  const state = req.body.state
  const role_id = req.body.role_id
  const department_id = req.body.department_id

  let [check_repeate_phone, phone_data] = await check_if_exists('login', 'phone', phone, res)
  if (Array.isArray(phone_data)) phone_data = phone_data[0]
  
  // 拿phone参数去查，
  // 1、能查到结果：
  //  1.1、查询结果的user_id和当前这条修改数据的user_id是‘不一样’，说明你想要的这个账号，别人已经在用了，得换一个啊～
  //  1.1、查询结果的user_id和当前这条修改数据的user_id是‘一样’，那继续其它逻辑～
  // 2、查询结果为空，那继续其它逻辑～    

  if(check_repeate_phone == sqlCheckType.True){
    if(update_id != phone_data.id) {
      console.log('该手机号已经存在! ')
      err_reply('user/update', res, '该手机号已经存在!')
      return
    }
  }

  // SQL
  const sql_update = `UPDATE userInfo SET  nick_name = '${nick_name}' , sex = '${sex}', phone = '${phone}',
   head_url = '${head_url}', state = ${state}, role_id = ${role_id}, department_id = ${department_id} 
   WHERE user_id = ${update_id};`
  console.log('user_update---' + sql_update)
  // 发送请求
  dbconfig.sqlConnect(sql_update, [], (err, data) => {
    if(err) {
      console.log('修改出错')
      console.log('打印SQL语句' + JSON.stringify(sql_update))
      console.log(JSON.stringify(err))
      err_reply('user/update', res, err.sqlMessage)
    } else{
      console.log('用户修改成功')
      console.log(data)
      if (!data.affectedRows || data.affectedRows == 0){
        console.log(`该修改的user_id异常`)
        // 响应客户端请求
        err_reply('/user/update',res,`用户修改请求异常`)
        return
      }
      // 响应客户端请求
      success_reply('user/update', res, '用户修改成功！', update_id ?? '')
    }
  })
}

/** 
 *  @description 获取用户列表
 * */ 
// // 查询类型
// const QueryType = {
//   QUERY_ALL : 0, //查询所有
//   QUERY_PAGE : 1, // 分页查询
//   QUERY_CONDITION : 2, // 条件查询
// }

const user_list = async function (req, res, next) {
  console.log('\n\n接收 userList请求（userInfo），参数user_id是：' + req.query.user_id)
  console.log('请求头：' + JSON.stringify(req.headers))
  console.log('\n-------\n' + JSON.stringify(req.query))
  
  if(!req.headers || req.headers.length == 0){
    err_reply('/user/list', res, '请求失败，token不能为空')
    return
  }
  // 从query获取参数
  const user_id = req.query.id // 用户ID
  const account = req.query.account // 账号
  const nick_name = req.query.nick_name // 真实姓名
  const phone = req.query.phone // 手机号
  const state = req.query.state // 状态
  const create_time = req.query.create_time // 创建时间
  const limit = Number(req.query.limit) ?? 1000 //限制一次查询多少条，默认1000条
  const pageIndex = Number(req.query.pageIndex) ?? 1 // 要查询第几页数据
  if (pageIndex < 0) pageIndex = 1
  const offset = (pageIndex - 1) * limit
  if (offset < 0) offset = 0
  
  // 拼接参数，并加入到数组params
  var params = []
  if (user_id)  params.push([`user_id = '${user_id}'`])
  if (account)  params.push([`account = '${account}'`])
  if (nick_name)  params.push([`nick_name LIKE '${nick_name}%'`])
  if (phone)  params.push([`phone = '${phone}'`])
  if (state)  params.push([`state = '${state}'`])
  if (create_time)  params.push([`create_time = '${create_time}'`])

  console.log('\nparams---' + params)
  console.log('\nlimit---' + limit)
  console.log('\noffset---' + offset)

  // var sql_check_limit = `SELECT t1.*, t2.role_name FROM ${`userInfo`} t1 LEFT JOIN role t2 on t1.role_id = t2.id`
  var sql_check_limit = `SELECT T5.* FROM (SELECT t1.*, t2.account, t2.password, t3.role_name, t4.depart_name 
    FROM ${`userInfo`} t1 LEFT JOIN ${`login`} t2 ON t1.user_id = t2.id 
    LEFT JOIN ${`role`} t3 ON t1.role_id = t3.role_level 
    LEFT JOIN ${`department`} t4 ON t1.department_id = t4.id) T5 `
  const sql_check_limit_data = await check_plublic(sql_check_limit, false)
  console.log('sql_check_limit_data--' + JSON.stringify(sql_check_limit_data))
  if (limit > 0 && offset >= 0) {
    // 说明当前请求是分页查询，进入这里是为了查询符合套件的总数
    // var sql_check_count = `SELECT count(1) FROM ${`userInfo`} t1 LEFT JOIN role t2 on t1.role_id = t2.id`
    var sql_check_count = `SELECT count(1) FROM (SELECT t1.*, t2.account, t2.password, t3.role_name, t4.depart_name 
      FROM ${`userInfo`} t1 LEFT JOIN ${`login`} t2 ON t1.user_id = t2.id 
      LEFT JOIN ${`role`} t3 ON t1.role_id = t3.role_level 
      LEFT JOIN ${`department`} t4 ON t1.department_id = t4.id) T5 `
    const sql_check_count_data = await check_plublic(sql_check_count, true)
    console.log('sql_check_count_data--' + JSON.stringify(sql_check_count_data))
    
    const count1 = sql_check_limit_data.length
    const count2 = sql_check_count_data[0]['count(1)']
    console.log('～分页返回总个数是：' + count1)
    console.log('～统计总个数是：' + sql_check_count_data[0]['count(1)'])
    success_reply2('/userList', res, '查询成功', sql_check_limit_data, count2)
  }else {
    // 属于不分页的查询，那么自然
    const count = sql_check_limit_data.length
    console.log('分页返回总个数是：' + count)
    success_reply2('/userList', res, '查询成功', sql_check_limit_data, count)
  }
  console.log('所有请求都结束了！')
  // 抽取这部分代码
  // @params sql_check：查询的SQL语句（非条件那部分）
  // params isConditionAll： 是否统计符合条件的总个数查询（'select count(1) xxx'）
  function check_plublic(sql_check, isConditionAll) {
  
    return new Promise((resolve,reject) => {
      if(params.length > 0) {
        console.log('条件查询，正在拼凑sql_check～～')
        sql_check = sql_check + ' WHERE'
        var condition = ' '
        for (let index = 0; index < params.length; index++) {
          const element = params[index];
          // 拼接WHERE条件后面的SQL语句
          if(index == 0) condition = condition + `${element[0]}`
          else condition = condition + ' AND ' + `${element[0]}`
        }
        // 拼凑完整的SQL语句
        sql_check = sql_check + condition
      }
      //  是否分页查询
      if (!isConditionAll && limit > 0 && offset >= 0) {
        sql_check = sql_check + ` ORDER BY user_id LIMIT ${limit} OFFSET ${offset}; `
      }
      
      console.log('打印查询语句：' + sql_check)
  
      var callBack = (err,data) => {
        console.log("userInfo -> err: " + err)
        console.log("userInfo -> 请求返回(data): " + JSON.stringify(data))
        if (err) {
          console.log('，查询出错了 err is: ' + err)
          err_reply('/userList', res, `查询数据异常，请联系管理员，并提供用户ID：${user_id}`)
  
        } else {
          console.log('手机号数据，查询成功')
          if(data === null){
            console.log('用户列表-查询异常!')
            err_reply('/userList', res, `该user_id数据不存在，请联系管理员，并提供用户ID：${user_id}`)
            
          }else {
            console.log('数据查询成功!')
            // success_reply('/userList', res, '查询成功', data)
            console.log('\n\n我要返回数据咯？！\n\n')
            // return data
            resolve(data)
          }
        }
      }
      dbConfig.sqlConnect(sql_check, [], callBack)
    })
  }
}

// @description 用户删除
const user_delete = (req, res) => {
  console.log('user_delete ---')
const arr = req.body.params
let condition = ""
arr.forEach(element => {
  const element_id = element.user_id.toString()
  if(condition.length === 0){
    condition = `${element_id}`
  } else {
    condition = `${condition},${element_id}`
  }
});
console.log('打印一下condition---' + condition)
// const sql_delete = `DELETE FROM ${`userInfo`} WHERE user_id in (${condition})`
// 表关联，删登录表，用户表也会联动删除
const sql_delete = `DELETE FROM ${`login`} WHERE id in (${condition})`
console.log('打印一下sql_delete---' + sql_delete)

var callBack = (err,data) => {
    console.log("err: " + err)
    console.log("data: " + JSON.stringify(data))
    // {"fieldCount":0,"affectedRows":1,"insertId":0,"serverStatus":2,"warningCount":0,"message":"","protocol41":true,"changedRows":0}
    if (err) {
      console.log('/user/delete 请求出错了')
      // 响应客户端请求
      err_reply('/user/delete',res,`该用户删除失败`)
      return;
    } else {
      console.log(`/user/delete 请求成功 -- 删除成功`)
      // 响应客户端请求
      success_reply('/dep',res,'删除成功',{})
    }
  }
  dbConfig.sqlConnect(sql_delete, [], callBack)
}

//   //  查询某张表，共多少条数据
// function selectCount(tableName, dbConfig,complete) {
//   const sql_check = `select id from${`tableName`}`
//   dbConfig.sqlConnect(sql_check,[],(err, data)=>{
//     complete(err,data)
//   })
// }

module.exports = { user_list, user_delete, user_add, user_update }
